import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Modal, Button } from 'antd';
import PateoTable from '../../../../components/common/PateoTable';
import PateoAuthButtons from '../../../../components/common/PateoAuthButtons';
import PropTypes from "prop-types";
import Ellipsis from '../../../../components/Ellipsis';
import {getDicByKey} from "@/support/common";
import SmsModal from "../Modal/SmsModal"
import {filterAuth} from "@/support/common";

@connect((state: any) => ({
    messageChannel: state.messageChannel,
    loading: state.loading.effects['messageChannel/getFetchPage'],
}))
export default class SmsTable extends PureComponent<any, any> {

    static contextTypes = {
        permissions: PropTypes.array,
        dicData: PropTypes.object,
    };

    constructor(props: any) {
        super(props);
        this.state = {
            visible: false,
            formData: {},
        };
    }

    componentDidMount() {
        this.handleFlush();
    }

    handleRemove = (record: any) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'messageChannel/getDataWithRes',
            payload: { url: '/message/channel/relationSms', smsCd: record.smsCd },
            callback: (response: any) =>{
                if(response.data){
                    message.error("该推送服务渠道被消息推送模板引用，不允许删除。")
                } else {
                    Modal.confirm({
                        title:"是否确认删除？",
                        onOk: () => this.handleDelete(record.smsCd)
                    })
                }
            }
        });
    }

    handleDelete = (smsCd: any) =>{
        const { dispatch } = this.props;
        dispatch({
            type: 'messageChannel/getDataWithRes',
            payload: { url: '/message/channel/deleteSms', smsCd },
            callback: (response: any) =>{
                response.statusCode === "0" ? message.success("删除成功") : message.error(response.statusMessage);
                this.handleFlush();
            }
        });
    };
    handleEdit = (record: any) =>{
        const { dispatch } = this.props;
        dispatch({
            type: 'messageChannel/getData',
            payload: { url: '/message/channel/relationSms', smsCd: record.smsCd },
            callback: (response: any) =>{
                if(response.data){
                    Modal.confirm({
                        title:"推送服务渠道被消息推送模板引用，是否确定修改？",
                        onOk: () => this.setState({ visible: true, formData: record })
                    })
                } else {
                    this.setState({ visible: true, formData: record })
                }
            }
        });
    };

    handleFlush = () =>{
        const { dispatch } = this.props;
        dispatch({
            type: 'messageChannel/getFetchPage',
            payload: { url: "/message/channel/findSmsByPage"}
        });
    };

    render() {
        const { messageChannel: { pageData: { list, pagination } }, loading, dispatch, handleGoBack, pathname } = this.props;
        const { formData, visible } = this.state;
        const columns=[
            {
                title: '短信编号',
                dataIndex: 'smsCd',
                render:(text: any)=><Ellipsis  length={16} tooltip>{text}</Ellipsis>
            }, {
                title: '短信平台',
                dataIndex: 'platform',
                render: (text: any) => {
                    if(text != null){
                        const platformStr = getDicByKey(this.context.dicData,"messageCenterSms",text+'')
                        return platformStr == text ? '其他平台' : platformStr;
                    }else{
                        return '';
                    }
                }
            }, {
                title: '应用Key',
                dataIndex: 'appKey',
                render:(text: any)=><Ellipsis  length={16} tooltip>{text}</Ellipsis>
            }, {
                title: '短信平台主机地址',
                dataIndex: 'host',
                render:(text: any)=><Ellipsis  length={16} tooltip>{text}</Ellipsis>
            }, {
                title: '短信平台服务端口',
                dataIndex: 'port',
            }, {
                title: '短信平台通道',
                dataIndex: 'channel',
            }, {
                title: '企业代码',
                dataIndex: 'corpId',
                render:(text: any)=><Ellipsis  length={16} tooltip>{text}</Ellipsis>
            },  {
                title: 'jasper key',
                dataIndex: 'licenseKey',
                render:(text: any)=><Ellipsis  length={16} tooltip>{text}</Ellipsis>
            }, {
                title: '创建人',
                dataIndex: 'createBy',
            },{
                title: '创建时间',
                dataIndex: 'createDate',
            }, {
                title: '修改时间',
                dataIndex: 'updateDate',
            },{
                title: '操作',
                dataIndex: '操作',
                width: 200,
                fixed: 'right',
                align: 'center',
                render: (text: any, record: any) => {
                    const btns = [
                        {
                            title: '编辑',
                            key: 'edit',
                            auth: 'messageChannelConfig_doEdit',
                            onConfirm: () => this.handleEdit(record),
                        },
                        {
                            title: '删除',
                            key: 'delete',
                            auth: 'messageChannelConfig_doDel',
                            onConfirm: () => this.handleRemove(record) ,
                        }];
                    return <PateoAuthButtons btns={btns} max={2} pathname={pathname}/>;
                },
            }];
        const paginationProps = {
            showSizeChanger: true,
            showQuickJumper: true,
            ...pagination,
            showTotal: () => (
                <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
            ),
        };
        const tableProps = {
            columns,
            rowKey: (record: any) => record.smsCd,
            dataSource: list,
            loading,
            pagination: paginationProps,
            scroll: { x: 'max-content' }
        };
        return (
            <div>
                <Card bordered={false}>
                    <div style={{ marginTop: 24 }}>
                        <Button onClick={() => handleGoBack()} size={"small"} type="primary" ghost style={{marginRight: 10}}>
                            返回
                        </Button>
                        {
                            filterAuth("messageChannelConfig_doAdd", this.context.permissions, pathname) &&
                            <Button onClick={() => this.setState({ visible: true })} size={"small"} type="primary" ghost style={{marginRight: 10}}>
                                新增
                            </Button>
                        }
                        <Button onClick={() => this.handleFlush()} size={"small"} type="primary" ghost style={{marginRight: 10}}>
                            刷新
                        </Button>
                    </div>
                    <div style={{ marginTop: 24}}>
                        <PateoTable
                            tableProps={tableProps}
                            dispatch={dispatch}
                            fetchUrl="messageChannel/getFetchPage"
                            parameterUrl="/message/channel/findSmsByPage"
                            currentName ="page"
                            pageSizeName='size'
                        />
                    </div>
                    <SmsModal
                        changeVisible={() => this.setState({ visible: false, formData: {} })}
                        visible={visible}
                        formData={formData}
                        handleFlush={this.handleFlush}
                    />
                </Card>
            </div>
        )
    }
}
